package com.earl.qrcode.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.earl.qrcode.entitys.Video;
import com.earl.qrcode.entitys.blackqacode;
import com.earl.qrcode.repository.BlackqacodeRepository;
import com.earl.qrcode.repository.VideoRepository;

@Service
public class VideoService extends MyService {

	@Autowired
	private VideoRepository videoRepository;
	
	@Autowired
	private  BlackqacodeRepository blackqacode;

	
	
	@Transactional
	public String saveVideo(MultipartFile videoFile, HttpServletRequest request, Video video, String modeName) throws IOException {
		String videoName = UUID.randomUUID().toString() + videoFile.getOriginalFilename();
		Calendar calendar = Calendar.getInstance();
		String newFolderPath = "videos/" + calendar.get(Calendar.YEAR) + "/" + calendar.get(Calendar.MONTH) + "/"
				+ calendar.get(Calendar.DATE);
		String videoFolder = request.getServletContext().getRealPath("/") + newFolderPath;

		File folder = new File(videoFolder);
		if (!folder.exists()) {
			folder.mkdirs();
		}

		File file = new File(videoFolder +"/"+ videoName);

		InputStream in = videoFile.getInputStream();
		FileOutputStream out = new FileOutputStream(file);

		int len = 0;
		byte[] bys = new byte[1024];
		while ((len = in.read(bys)) != -1) {
			out.write(bys, 0, len);
		}

		out.close();
		in.close();
		
		video.setVideoAddress(getDomainName() + "/" + newFolderPath + "/" + videoName);
		Integer videoId = videoRepository.save(video).getVideoId();

		return getDomainName() + "/videos/" + modeName + "/" + videoId;
	}
	
	public Video findVideoById(Integer id){
		
		return  videoRepository.findOne(id);
	}

	
	public void savablackqacode(String blackqacodeName,int whiteId,int qrcodeId){
		blackqacode blackqacodea=new blackqacode(blackqacodeName, whiteId,qrcodeId);
		  blackqacode.save(blackqacodea);
	}
	
	
	
}
